<template>
  <el-upload
    class="avatar-uploader"
    :http-request="upload"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <el-image
      v-if="imageUrl"
      :src="imageUrl"
      fit="cover"
      class="avatar"
    />
    <el-icon
      v-else
      class="avatar-uploader-icon"
    >
      <Plus />
    </el-icon>
    <template #tips>
      <div
        style="color: rgba(153, 153, 153, 1)"
        class="el-upload__tip"
      >
        注: 格式为png, jpg, jpeg等, 文件小于2M, 最多可上传8张
      </div>
    </template>
  </el-upload>
</template>

<script lang="ts" setup>
import { ref, defineEmits, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { httpUpload } from '@/api/upload'
import type { UploadFile, UploadProps, UploadRequestOptions } from 'element-plus'

const emit = defineEmits<(e: 'onSuccess', url: string) => void>()
const props = withDefaults(defineProps<{ url: string }>(), {
  url: ''
})
const imageUrl = ref(props.url)

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  _response,
  uploadFile: UploadFile
): void => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw as any)
}
const upload = (options: UploadRequestOptions): any => {
  const formData = new FormData()
  formData.append('file', options.file)
  formData.append('type', options.file.type)
  httpUpload(formData).then((res: any) => {
    imageUrl.value = res
    emit('onSuccess', res)
  })
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
</script>

  <style scoped>
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  </style>

  <style>
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .avatar {
    width: 120px;
    height: 120px;
    padding: 1px;
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  </style>
